//
//  OPKWebViewController.m
//  YCOpenSDK
//
//  Created by ycgame on 2020/9/23.
//

#import "OPKWebViewController.h"
#import "OPKWebViewScriptMessageObject.h"
#import "OpenSDK.h"
#import "OpenSDK_LoginLoadingView.h"
#import "OpenSDK_LoginManager.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_DataManager.h"
#import "OpenSDK_UIUtil.h"
#import "OpenSDK_UIManager.h"
#import "OPKMach.h"
#import "OpenSDK_DataKeys.h"
#import <Y2Common/Y2Common.h>
// webview key path
#define OPK_KP_TITLE @"title"
#define OPK_KP_CAN_GO_BACK @"canGoBack"
#define OPK_KP_CAN_GO_FORWARD @"canGoForward"
#define OPK_KP_ESTIMATED_PROGRESS @"estimatedProgress"

#define OPK_WMN_INIT @"init"
#define OPK_WMN_EXIT @"exit"
#define OPK_WMN_LOGIN_INVALID @"UserTokenInvalid"
#define OPK_WMN_SWITCH_ACCOUNT @"switchAccount"
#define OPK_WMN_ACCOUNT_BIND @"bindAccount"
#define OPK_WMN_REAL @"real"
#define OPK_WMN_MODIFY_MAIL @"modifyMail"
#define OPK_WMN_MODIFY_MOBILE @"modifyMobile"
#define OPK_WMN_BIND_MOBILE @"bindMobile"
#define OPK_WMN_UNBIND_OTHER @"unbindOther"
#define OPK_WMN_LOGIN @"login"
#define OPK_WMN_LOGOUT @"logout"
#define OPK_WMN_VIP_LOGIN @"loginCustomerService"
#define OPK_WMN_VIP_OPEN @"openCustomerService"
#define OPK_WMN_VIP_GAME_LOGIN @"loginGameCustomerService"

#define OPK_WK_CALLBACK @"callback"

@interface OPKWebViewController ()<WKUIDelegate, WKNavigationDelegate, OPKWebViewScriptMessageDelegate>
@property (nonatomic, strong)WKWebView *webView;
@property (nonatomic, strong)OPKWebViewScriptMessageObject *scriptMessageObj;
@property (nonatomic, strong)UIActivityIndicatorView * activityIndicator;
@property (nonatomic, strong)UIButton *failedBackButton;

@end

@implementation OPKWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    // Do any additional setup after loading the view from its nib.
    [self initializeComponents];
    
    [self webViewLoadUrl:_url];
}

- (void)dealloc {
    [_webView.configuration.userContentController removeAllUserScripts];
    //移除观察者
    [_webView removeObserver:self forKeyPath:OPK_KP_TITLE];
    [_webView removeObserver:self forKeyPath:OPK_KP_CAN_GO_BACK];
    [_webView removeObserver:self forKeyPath:OPK_KP_CAN_GO_FORWARD];
    [_webView removeObserver:self forKeyPath:OPK_KP_ESTIMATED_PROGRESS];
    NSLog(@"web dealloc");
}

// 初始化一些控件
- (void)initializeComponents {
    
    _scriptMessageObj = [[OPKWebViewScriptMessageObject alloc] initWithDelegate:self];
    WKUserContentController *userController = [[WKUserContentController alloc] init];
    
    // 注册所有消息
    NSArray *msgNames = @[OPK_WMN_INIT,
                          OPK_WMN_EXIT,
                          OPK_WMN_SWITCH_ACCOUNT,
                          OPK_WMN_ACCOUNT_BIND,
                          OPK_WMN_REAL,
                          OPK_WMN_MODIFY_MAIL,
                          OPK_WMN_MODIFY_MOBILE,
                          OPK_WMN_BIND_MOBILE,
                          OPK_WMN_LOGIN,
                          OPK_WMN_LOGOUT,
                          OPK_WMN_VIP_LOGIN,
                          OPK_WMN_VIP_OPEN,
                          OPK_WMN_VIP_GAME_LOGIN,
                          OPK_WMN_UNBIND_OTHER,
                          OPK_WMN_LOGIN_INVALID];
    for (NSString *name in msgNames) {
        [userController addScriptMessageHandler:_scriptMessageObj name:name];
    }
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.allowsInlineMediaPlayback = NO;
    config.userContentController = userController;
    _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    _webView.allowsBackForwardNavigationGestures = YES;
    _webView.scrollView.showsVerticalScrollIndicator = NO;
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    if (@available(iOS 11.0, *)) {
        _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    
    [self.webView addObserver:self
                   forKeyPath:OPK_KP_TITLE
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:OPK_KP_CAN_GO_BACK
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:OPK_KP_CAN_GO_FORWARD
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:OPK_KP_ESTIMATED_PROGRESS
                      options:0
                      context:nil];
    [self.view addSubview:_webView];
    
    _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:_activityIndicator];
    
    _failedBackButton = [[UIButton alloc] init];
    [_failedBackButton setTitle:@"加载失败，点击返回" forState:UIControlStateNormal];
    [_failedBackButton setTitleColor:[UIColor systemBlueColor] forState:UIControlStateNormal];
    _failedBackButton.titleLabel.font = [UIFont systemFontOfSize:11];
    [_failedBackButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [_failedBackButton setHidden:YES];
    [self.view addSubview:_failedBackButton];
    
    [self makeConstraints];
}

// 添加约束
- (void)makeConstraints {
    _webView.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *webTopConstraint = [NSLayoutConstraint constraintWithItem:_webView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
    NSLayoutConstraint *webLeftConstraint = [NSLayoutConstraint constraintWithItem:_webView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0];
    NSLayoutConstraint *webRightConstraint = [NSLayoutConstraint constraintWithItem:_webView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:0];
    NSLayoutConstraint *webBottomConstraint = [NSLayoutConstraint constraintWithItem:_webView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
    [self.view addConstraints:@[webTopConstraint, webLeftConstraint, webRightConstraint, webBottomConstraint]];
    
    _activityIndicator.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *indicatorCenterX = [NSLayoutConstraint constraintWithItem:_activityIndicator attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    NSLayoutConstraint *indicatorCenterY = [NSLayoutConstraint constraintWithItem:_activityIndicator attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    NSLayoutConstraint *indicatorWidth = [NSLayoutConstraint constraintWithItem:_activityIndicator attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0 constant:50];
    NSLayoutConstraint *indicatorHeight = [NSLayoutConstraint constraintWithItem:_activityIndicator attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:0 constant:50];
    [self.view addConstraints:@[indicatorCenterX, indicatorCenterY, indicatorWidth, indicatorHeight]];
    
    
    _failedBackButton.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *backButtonCenterX = [NSLayoutConstraint constraintWithItem:_failedBackButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    NSLayoutConstraint *backButtonCenterY = [NSLayoutConstraint constraintWithItem:_failedBackButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    NSLayoutConstraint *backButtonWidth = [NSLayoutConstraint constraintWithItem:_failedBackButton attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0 constant:150];
    NSLayoutConstraint *backButtonHeight = [NSLayoutConstraint constraintWithItem:_failedBackButton attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:0 constant:40];
    [self.view addConstraints:@[backButtonCenterX, backButtonCenterY, backButtonWidth, backButtonHeight]];
}

- (void)webViewLoadUrl:(NSString *)url {
    NSURL *URL = [[NSURL alloc] initWithString:url];
    if (URL == nil) { return; }
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
    
    NSString *customUserAgent = @"yunchanggameios";
    __weak typeof(self) weakSelf = self;
    [_webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSString *userAgent = result;
        NSString *newUserAgent;
        if (![result containsString:customUserAgent]) {
            newUserAgent = [userAgent stringByAppendingString:customUserAgent];
        }else{
            newUserAgent = result;
        }
        if (@available(iOS 9.0, *)) {
            [weakSelf.webView setCustomUserAgent:newUserAgent];
        } else {
            // Fallback on earlier versions
            [weakSelf.webView setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
        }
    }];
    
    [_webView loadRequest:request];
}

- (void)backAction:(UIButton *)sender {
    [self dismiss];
}

#pragma mark - 用户事件
- (void)deleteWebCache {
    if (@available(iOS 9.0, *)) {
        //allWebsiteDataTypes清除所有缓存
        NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        }];
    } else {
        // Fallback on earlier versions
    }
}

#pragma mark - Plugin_WebViewScriptMessageDelegate
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    // 初始化
    if ([message.name isEqual:OPK_WMN_INIT]) {
        NSString *jsonStr = message.body;
        NSDictionary *data = [self jsonObjWithString:jsonStr];
        [self webInit:data];
    }
    // 切换账号
    else if ([message.name isEqual:OPK_WMN_SWITCH_ACCOUNT]) {
        [self switchAccount];
    }
    // 登录
    else if ([message.name isEqual:OPK_WMN_LOGIN]) {
        [self login];
    }
    // 登出
    else if ([message.name isEqual:OPK_WMN_LOGOUT]) {
        [self logout];
    }
    // 第三方账号绑定
    else if ([message.name isEqual:OPK_WMN_ACCOUNT_BIND]) {
        NSString *jsonStr = message.body;
        NSDictionary *data = [self jsonObjWithString:jsonStr];
        [self bindWithType:data];
    }
    // 手机号绑定
    else if ([message.name isEqual:OPK_WMN_BIND_MOBILE]) {
        [self bindPhone];
    }
    // 实名认证
    else if ([message.name isEqual:OPK_WMN_REAL]) {
        [self goReal];
    }
    // 修改手机号
    else if ([message.name isEqual:OPK_WMN_MODIFY_MOBILE]) {
        NSString *jsonStr = message.body;
        NSDictionary *data = [self jsonObjWithString:jsonStr];
        [self modifyMobile:data];
    }
    // 修改邮箱
    else if ([message.name isEqual:OPK_WMN_MODIFY_MAIL]) {
        
    }
    // 解绑第三方账号
    else if ([message.name isEqual:OPK_WMN_UNBIND_OTHER]) {
        [self unbindOther:message.body];
    }
    // 客服登录
    else if ([message.name isEqual:OPK_WMN_VIP_LOGIN]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"VipCustomerService_openLogin" object:nil];
    }
    // 客服打开
    else if ([message.name isEqual:OPK_WMN_VIP_OPEN]) {
        [self openCustomerService];
    }
    // 游戏客服登录
    else if ([message.name isEqual:OPK_WMN_VIP_GAME_LOGIN]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"VipCustomerService_gameLoginAgain" object:nil];
    }
    // 退出
    else if ([message.name isEqual:OPK_WMN_EXIT]) {
        [self dismiss];
    }else if ([message.name isEqualToString:OPK_WMN_LOGIN_INVALID]){
        [self userTokenInvalid];
    }
}

- (NSDictionary *)jsonObjWithString:(NSString *)str {
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *data = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
    if (error) { return nil; }
    return data;
}

- (NSString *)jsonStringWithObject:(NSDictionary *)obj {
    NSError *error;
    NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:0 error:&error];
    if (error) { return @""; }
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

- (void)dismiss {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.navigationController != nil) {
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    });
}

- (void)webInit:(NSDictionary *)data {
    NSString *nickname = [OpenSDK_DataManager getInstance].getCurAccount.accountName;
    NSString *token = [OpenSDK_DataManager getInstance].getCurAccount.token;
    NSString *open_id = [OpenSDK_DataManager getInstance].getCurAccount.openId;
    NSString *user_id = [OpenSDK_DataManager getInstance].getCurAccount.userId;
    NSString *mobile = [OpenSDK_DataManager getInstance].getCurAccount.mobile;
    NSString *channel_id = [OpenSDK_DataManager getInstance].channelID;
    NSString *app_id = [OpenSDK_DataManager getInstance].appID;
    NSString *platform = @"IOS";
    NSString *device_id = [Y2DeviceInfo getDeviceID];
    NSString *pub_key = [OpenSDK_DataManager getInstance].appPubKey ?: @"";
    NSMutableString *loginTypes = [[NSMutableString alloc] init];
    for (NSString *type in [OpenSDK_DataManager getInstance].supportLoginTypes) {
        [loginTypes appendFormat:@"%@,", type];
    }
    [loginTypes deleteCharactersInRange:NSMakeRange(loginTypes.length - 1, 1)];
    
    nickname = nickname == nil ? @"" : nickname;
    token = token == nil ? @"" : token;
    open_id = open_id == nil ? @"" : open_id;
    user_id = user_id == nil ? @"" : user_id;
    mobile = mobile == nil ? @"" : mobile;
    channel_id = channel_id == nil ? @"" : channel_id;
    app_id = app_id == nil ? @"" : app_id;
    device_id = device_id == nil ? @"" : device_id;
    
    NSDictionary *params = @{
        @"nick_name": nickname,
        @"token": token,
        @"open_id": open_id,
        @"channel_id": channel_id,
        @"channel": channel_id,
        @"app_id": app_id,
        @"platform": platform,
        @"device_id": device_id,
        @"user_id": user_id,
        @"mobile": mobile,
        @"public_key": pub_key,
        @"login_types": loginTypes.copy,
        @"opensdk_version": @"2.0"
    };
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSString *callBack = data[OPK_WK_CALLBACK];
    [_webView evaluateJavaScript:[NSString stringWithFormat:@"%@('%@')", callBack, jsonStr] completionHandler:nil];
}

// 切换账号
- (void)switchAccount {
    [self.navigationController dismissViewControllerAnimated:NO completion:^{
//        [[OpenSDK_UIManager getInstance] showSwitchAccountUI];
//        [[OpenSDK getInstance].delegate openSDKSwitchAccountWithMessage:@"OpenSDK切换帐号，自动弹出登录框"];
        [[OpenSDK_LoginManager getInstance] localLogoutNotClean];
    }];
}

// 登录
- (void)login {
    [self.navigationController dismissViewControllerAnimated:NO completion:^{
        [[OpenSDK_UIManager getInstance] showLoginUI];
    }];
}

- (void) userTokenInvalid{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.navigationController != nil) {
            [self.navigationController dismissViewControllerAnimated:YES completion:^{
                [[OpenSDK_UIManager getInstance] loginInvalid];
            }];
        } else {
            [self dismissViewControllerAnimated:YES completion:^{
                [[OpenSDK_UIManager getInstance] loginInvalid];
            }];
        }
    });
}

// 登出
- (void)logout {
    [[OpenSDK_LoginManager getInstance] localLogout];
    [[OpenSDK getInstance].delegate openSDKLoginOutWithMessage:@"OpenSDK主动退出登录"];
}

- (void)bindWithType:(NSDictionary *)data {
    NSString *type = data[@"authType"];
    NSString *callBack = data[OPK_WK_CALLBACK];
    if (type == nil) { return; }
    // 再调用第三方验证
    [[OpenSDK_LoginManager getInstance] authWithPlatform:type delegate:^(BOOL result, NSDictionary *content, long errorNo, NSString *err) {
        if (result) {
            NSData *data = [NSJSONSerialization dataWithJSONObject:content options:0 error:nil];
            NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@('%@')", callBack, jsonStr] completionHandler:nil];
        } else {
            [self.webView evaluateJavaScript:[NSString stringWithFormat:@"%@('')", callBack] completionHandler:nil];
        }
    }];
}

// 去实名认证
- (void)goReal {
    [self.navigationController dismissViewControllerAnimated:NO completion:^{
        [[OpenSDK_UIManager getInstance] showRealUI];
    }];
}

// 绑定手机
- (void)bindPhone {
    [self.navigationController dismissViewControllerAnimated:NO completion:^{
        [[OpenSDK_UIManager getInstance] showBindPhoneUI];
    }];
}

// 修改手机
- (void)modifyMobile:(NSDictionary *)data {
    NSString *mobile = data[@"mobile"];
    if (mobile == nil || mobile.length == 0) { return; }
    OpenSDK_AccountRecord *account = [OpenSDK_DataManager getInstance].getCurAccount;
    [[OpenSDK_DataManager getInstance] removeAccount:account];
    [account setAccountName:mobile];
    [account setAccountValue:mobile];
    [[OpenSDK_DataManager getInstance] setCurAccount:account];
}

// 第三方登录解绑
- (void)unbindOther:(NSString *)type {
    OpenSDK_AccountRecord *account = [OpenSDK_DataManager getInstance].getCurAccount;
    // 如果当前登录方式为第三方登录除一键登录的其他登录方式，则更新账号信息
    if (account.accountType == OpenSDKAccountTypeOther && [account.platform isEqual:type]) {
        [[OpenSDK_DataManager getInstance] removeAccount:account];
        [account setAccountType:OpenSDKAccountTypeDynamic];
        [[OpenSDK_DataManager getInstance] setCurAccount:account];
    }
}

// 打开客服
- (void)openCustomerService {
    NSString *nickname = [OpenSDK_DataManager getInstance].getCurAccount.accountName;
    nickname = nickname == nil ? @"" : nickname;
    NSString *rom = [OPKMach getTotalDiskSize];
    NSString *ram = [OPKMach getTotalMemorySize];
    NSDictionary *data = @{@"role_name": nickname,
                           @"server_name": @"",
                           @"os": @"iOS",
                           @"network": @"",
                           @"rom": rom,
                           @"ram": ram};
    NSString *jsonString = [self jsonStringWithObject:data];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"VipCustomerService_openKeFu" object:jsonString];
}

#pragma KVO
//kvo 监听进度
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if (object == _webView) {
        if ([keyPath isEqual:OPK_KP_TITLE]) {
            self.navigationItem.title = _webView.title;
        } else if ([keyPath isEqual:OPK_KP_CAN_GO_BACK]) {
            
        } else if ([keyPath isEqual:OPK_KP_CAN_GO_FORWARD]) {
            
        } else if ([keyPath isEqual:OPK_KP_ESTIMATED_PROGRESS]) {
        
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"页面开始加载...");
    [_activityIndicator startAnimating];
    [_failedBackButton setHidden:YES];
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"页面加载失败");
    [_activityIndicator stopAnimating];
    [_failedBackButton setHidden:NO];
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSLog(@"开始返回内容");
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"页面加载完成");
    [_activityIndicator stopAnimating];
    [_failedBackButton setHidden:YES];
}

//提交发生错误时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
}

// 接收到服务器跳转请求即服务重定向时之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"重定向");
}

// 根据WebView对于即将跳转的HTTP请求头信息和相关信息来决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 根据客户端受到的服务器响应头以及response相关信息来决定是否可以跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
}

//加载不受信任的https
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
    }
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    if (message == nil) { return; }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
    completionHandler();
}

//进程被终止时调用
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    NSLog(@"进程终止");
}

@end

